using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net;

namespace StormModelToKMLDB
{
    public class BuoyGetter
    {
        #region Events
        /// <summary>
        /// Handler for when the BuoyGetter successfully retrieves buoy Data
        /// </summary>
        /// <param name="models">the list of buoy objects that it built from buoy data</param>
        public delegate void BuoysRetrievedHandler(List<Storm> models);
        /// <summary>
        /// The event that fires when the BuoyGetter successfully retrieves buoy data
        /// </summary>
        public event BuoysRetrievedHandler BuoyssRetrieved;
        #endregion

        #region Private Members
        private Thread _getBuoyThread;
        //private Http _ftp;
        private int _sleepMillis;
        #endregion

        #region Constructors
        public BuoyGetter(int sleepMinutes)
        {
            //_ftp = new FTPClient();
            _sleepMillis = sleepMinutes * 1000 * 60;

            // Start Get Thread
            this._getBuoyThread = new Thread(new ThreadStart(this.RunGetBuoysThread));
            this._getBuoyThread.Name = "BuoyGetterThread";
            this._getBuoyThread.IsBackground = true;
        }
        #endregion

        #region Thread Method
        private void RunGetBuoysThread()
        {
            // Sleep time will vary, initialize to _sleepTimeMillis
            int millis = _sleepMillis;

            // Create a new list of storms
            List<Buoy> storms = new List<Buoy>();

            // Poll for data every <_sleepMillis> 
            while (true)
            {
                try
                {
                    //#region Connect
                    //HttpWebRequest req = HttpWebRequest.Create();
                    //_ftp.Timeout = 45000;
                    //_ftp.RemoteHost = "ftp.nhc.noaa.gov";
                    //_ftp.Connect();
                    //_ftp.Login("anonymous", "me@home.com");
                    //_ftp.ConnectMode = FTPConnectMode.PASV;
                    //_ftp.TransferType = FTPTransferType.ASCII;
                    //_ftp.ChDir("/pub/products/nhc/model");
                    //#endregion

                    //#region Check Connection
                    //if (!_ftp.IsConnected)
                    //{
                    //    millis = 60 * 1000;
                    //    throw new Exception("FTP client not connected...retrying in 60 secs");
                    //}
                    //#endregion

                    //#region Get most recent Storms and raise an event for those listening
                    //FTPFile[] detls = _ftp.DirDetails(".");
                    //ArrayList latest = new ArrayList();


                    //// Check the last 10 for age
                    //for (int i = 1; i < 11; i++)
                    //{
                    //    // Construct partial filename strings based on Date
                    //    DateTime now = DateTime.UtcNow;
                    //    string year = now.Year.ToString();
                    //    string month = string.Format("{0:00}", now.Month);
                    //    string day = string.Format("{0:00}", now.Day);
                    //    string partDT = year + month + day;

                    //    now = now.AddDays(-1);
                    //    year = now.Year.ToString();
                    //    month = string.Format("{0:00}", now.Month);
                    //    day = string.Format("{0:00}", now.Day);
                    //    string partDT1 = year + month + day;

                    //    // Previous 2 days (today + yesterday)
                    //    if (((FTPFile)detls[detls.Length - i]).Name.Contains(partDT) ||
                    //        ((FTPFile)detls[detls.Length - i]).Name.Contains(partDT1))
                    //    {
                    //        latest.Insert(0, detls[detls.Length - i]);
                    //    }
                    //}

                    //// Get and parse ALL of the most recent NHC data
                    //List<Storm> tmpList = new List<Storm>();
                    //foreach (FTPFile ff in latest)
                    //{
                    //    byte[] b = _ftp.Get(ff.Name);
                    //    foreach (Storm s in Storm.ParseNHC(b))
                    //    {
                    //        tmpList.Add(s);
                    //    }
                    //}

                    //// Now we have a list of recent storms, possibly duplicates that we should raise an event for
                    //if (this.ModelsRetrieved != null)
                    //    this.ModelsRetrieved(tmpList);

                    //#endregion

                }
                catch (Exception e)
                {
                    Console.WriteLine(DateTime.Now.ToString() + " " + Thread.CurrentThread.Name + ":\n" + e.Message + "\n");
                }
                finally
                {
                    #region Close Connection
                    //_ftp.Quit();
                    #endregion
                }
                try
                {
                    Thread.Sleep(millis);
                }
                catch (ThreadInterruptedException)
                {
                    return;
                }

                // Reset Sleep time to normal in case we slept short for an ftp connect problem
                millis = _sleepMillis;
            }
        }
        #endregion

        //#region Private Helpers
        //private List<string> GetFileNamesLast5Hours()
        //{
        //    DateTime nowUtc = DateTime.UtcNow;

        //    // Last 5 hrs
        //    for (int i = 1; i < 6; i++)
        //    {
        //        nowUtc = nowUtc.AddHours(-1);
        //        string h = nowUtc.Hour.ToString("{0:00}");

        //    }
            

        //}
        //#endregion
    }
}
